package com.sdhs.paas.internet.util;

import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;

import com.sdhs.paas.internet.util.regex.PathNameWildcardCompiler;

public class RequestURIFilter
{
  private final String[] uris;
  private final Pattern[] patterns;

  public RequestURIFilter(String uris)
  {
    if ((uris == null) || (uris.equals(""))) {
      uris = "";
    }
    List names = new LinkedList();
    List patterns = new LinkedList();

    for (String uri : uris.split(",")) {
      uri = uri.trim();

      if ((uri != null) && (!uri.equals(""))) {
        names.add(uri);
        patterns.add(PathNameWildcardCompiler.compilePathName(uri, 16384));
      }
    }

    if (!patterns.isEmpty()) {
      this.uris = ((String[])names.toArray(new String[names.size()]));
      this.patterns = ((Pattern[])patterns.toArray(new Pattern[patterns.size()]));
    } else {
      this.uris = new String[0];
      this.patterns = null;
    }
  }

  public boolean matches(HttpServletRequest request) {
    if (this.patterns != null) {
      String requestURI = request.getRequestURI();

      for (Pattern pattern : this.patterns) {
        if (pattern.matcher(requestURI).find()) {
          return true;
        }
      }
    }

    return false;
  }
  public boolean matches(String requestURI) {
    if (this.patterns != null)
    {
      for (Pattern pattern : this.patterns) {
        if (pattern.matcher(requestURI).find()) {
          return true;
        }
      }
    }

    return false;
  }
}
